package com.javaclimb.accounting.controller;

import com.javaclimb.accounting.po.Account;
import com.javaclimb.accounting.po.User;
import com.javaclimb.accounting.service.UserService;
import com.javaclimb.accounting.utils.CommonResult;
import com.javaclimb.accounting.utils.DesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/accounting")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 登录接口
     */
    //    http://localhost:8888/accounting/user/login?userName=zhangsan&userPassword=123456
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public Object login (User user){
        if(user.getUserName() == null || user.getUserPassword() == null){
            return CommonResult.failed("用户未注册，或密码错误");
        }
        //根据用户名查找对应的用户表记录
        User user1 = userService.login(user);
        if(user1 == null || !DesUtil.getDecryptString(user1.getUserPassword()).equals(user.getUserPassword())){
            return CommonResult.failed("用户未注册，或密码错误");
        }

        user1.setUserPassword(DesUtil.getDecryptString(user1.getUserPassword()));
        return CommonResult.success(user1,"登录成功");
    }

    /**
     * 注册
     */
    // http://localhost:8888/accounting/user/register
    @RequestMapping(value = "/user/register",method = RequestMethod.POST)
    public Object register( User user){
        //检验用户名是否已存在 检验身份证号与电话是否已存在
        List<User> users = userService.exists(user);
        if(users.size() != 0){
            return CommonResult.failed("注册失败，用户已存在！");
        }
        //注册 （先添加电子账户，再创建用户）
        Account account = new Account();
        account.setAccTemp(new BigDecimal(0));
        user.setUserPassword(DesUtil.getEncryptString(user.getUserPassword()));
        userService.register(user,account);
        return CommonResult.success("注册成功");
    }

    /**
     * 检验 根据用户名 真实姓名 手机号 邮箱 身份证号 5个条件
     */
    @RequestMapping(value = "/user/verify",method = RequestMethod.POST)
    public Object verify(User user){
        List<User> users = userService.verify(user);
        if(users.size() != 1){
            return CommonResult.failed("验证失败");
        }
        return CommonResult.success("验证成功！");
    }
}
